package com.doujiang.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.doujiang.domain.Favorite;
import com.doujiang.domain.dto.jhjNameCountDTO;

import com.doujiang.mapper.jhjFavoriteMapper;
import com.doujiang.service.jhjIFavoriteService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 收藏/想看Service业务层处理
 * 
 * @author 王伟舰
 * @date 2025-07-19
 */
@Service
public class jhjFavoriteServiceImpl extends ServiceImpl<jhjFavoriteMapper, Favorite> implements jhjIFavoriteService
{
    @Autowired
    private jhjFavoriteMapper favoriteMapper;

    @Override
    public List<Map<String, Object>> getTopActors() {
        List<Map<String, String>> rows = favoriteMapper.getFavoritedActorsAndTitles();
        Map<String, Integer> actorCountMap = new HashMap<>();
        Map<String, String> actorRepresentativeWork = new HashMap<>();

        for (Map<String, String> row : rows) {
            String actorLine = row.get("actors");
            String title = row.get("title");

            if (actorLine != null) {
                String[] actors = actorLine.split("[,，\\s]+");
                for (String actor : actors) {
                    if (!actor.trim().isEmpty()) {
                        actorCountMap.put(actor, actorCountMap.getOrDefault(actor, 0) + 1);
                        // 如果还没有代表作就设置为当前电影
                        actorRepresentativeWork.putIfAbsent(actor, title);
                    }
                }
            }
        }

        return actorCountMap.entrySet().stream()
                .sorted((e1, e2) -> e2.getValue().compareTo(e1.getValue()))
                .limit(5)
                .map(e -> {
                    Map<String, Object> m = new HashMap<>();
                    m.put("actor", e.getKey());
                    m.put("favorCount", e.getValue());
                    m.put("representativeWork", actorRepresentativeWork.get(e.getKey()));
                    return m;
                })
                .collect(Collectors.toList());
    }
    @Override
    public List<jhjNameCountDTO> getTopDirectorsByFavorite() {
        return favoriteMapper.getTopDirectorsByFavoriteWithWorks();
    }


}
